package cd.cdyb.sms.service.impl;


import cd.cdyb.sms.config.LoginUserSecurityDto;
import cd.cdyb.sms.dao.AdministratorsDao;
import cd.cdyb.sms.dao.EmployeeDao;
import cd.cdyb.sms.domain.Administrators;
import cd.cdyb.sms.domain.Employee;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {


    @Resource
    private EmployeeDao employeeDao;

    @Resource
    private AdministratorsDao administratorsDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String[] split = username.split("@");
        String type = split[0];

        LoginUserSecurityDto loginUserDto = new LoginUserSecurityDto();
        if ("CLIENT".equals(type)) {
            Employee employeeByPhone = employeeDao.getEmployeeByPhone(split[1]);

            // 根据名称去查数据库
            loginUserDto.setId(employeeByPhone.getEmployeeId());
            loginUserDto.setUsername(employeeByPhone.getUsername());
            loginUserDto.setPhone(employeeByPhone.getPhone());
            loginUserDto.setPassword(employeeByPhone.getPassword());
            loginUserDto.setCompanyId(employeeByPhone.getCompanyId());
        } else {
            Administrators administrators = administratorsDao.getAdministratorsByUsername(split[1]);
            // 根据名称去查数据库
            loginUserDto.setId(administrators.getAdministratorsId());
            loginUserDto.setUsername(administrators.getUsername());
            loginUserDto.setPassword(administrators.getPassword());
        }

        loginUserDto.setAccountNonExpired(true);
        loginUserDto.setAccountNonLocked(true);
        loginUserDto.setEnabled(true);
        loginUserDto.setCredentialsNonExpired(true);
//        // 权限列表
        return loginUserDto;
    }

}
